package com.zs.grain.ui

import android.app.Application
import android.media.AudioAttributes
import android.media.AudioManager
import android.media.MediaPlayer
import android.net.Uri
import android.os.Bundle
import android.util.Log
import androidx.lifecycle.MutableLiveData
import javax.inject.Inject
import com.zs.grain.service.DataService
import com.xnkj1688.semplibrary.mvvm.BaseViewModel
import android.widget.Toast
import com.jeremyliao.liveeventbus.LiveEventBus
import com.zs.grain.*
import com.zs.grain.device.EnumProducingStatus
import com.zs.grain.service.DeviceService
import com.zs.grain.service.SignalRService
import com.zs.grain.service.SoundService
import com.zs.grain.tool.clockManage.LocalDataBase
import io.reactivex.Completable
import io.reactivex.Single
import io.reactivex.schedulers.Schedulers
import java.util.*
import kotlin.concurrent.schedule


class WaitingViewModel @Inject constructor(
    val mApp: Application,
    val mDataService: DataService,
    val mDeviceService: DeviceService,
    val mSignalRService: SignalRService,
    val mSoundService: SoundService
) : BaseViewModel(mApp) {
    val process = MutableLiveData<String>()
    private var player: MediaPlayer? = null
    var orderId: Long = 0
        private set

    private fun getInstance() {
        player = MediaPlayer.create(
            mApp,
            R.raw.making
        )
    }
    private var mProgressTimer: Timer? = null

    init {
        process.value = "res://${mApp.packageName}/${R.mipmap.process0}"
    }

    fun playMusic() {
        if (player == null) {
            getInstance()
        }

        player?.isLooping = false;//true
        player?.setOnCompletionListener {
            if (player!!.isLooping) {
                player?.seekTo(0)
            }
        }
        player?.start()
    }

    fun init(orderId: Long) {
        //mSoundService.playSound2(4)
        process.value = "res://${mApp.packageName}/${R.mipmap.process0}"
        this.orderId = orderId
        Single.just(orderId)
            .observeOn(Schedulers.io())
            .subscribe({
                var order = mDataService.getOrder(it)
                if (order == null || order.details.size <= 0) {
                    this.onError("订单异常")
                    return@subscribe
                }

                if (mDeviceService.isHotting) {
                    process.postValue("res://${mApp.packageName}/${R.mipmap.hotting}")
                    var times = if (mDataService.isEmulator) 5 else 6000//60
                    for (i in 1..times) {
                        if (mDeviceService.isHotting) Thread.sleep(500)
                    }
                }

                this.startProgressTimer()
                order?.isSuccess = mDeviceService.make(order!!)
                mDeviceService.isMakingProduct = false
                //mDataService.insertLog("WVM")
                mDataService.save(order)
                if (!(order?.isSuccess ?: false)) {
                    mDataService.insertLog("Product:产品制作异常")
                    this.onError("产品制作异常")
                }
                mDataService.insertLog("Order:产品流程完成,本地单号:"+ mDataService.currentOrder?.id.toString())
                mDataService.currentOrder = null
                LiveEventBus.get("SyncService.DeleteMakingProduct").post("")
                LiveEventBus.get("SyncService.UploadOrder").post(order.id)
                LiveEventBus.get("SyncService.UploadComponents").post("")
            }, {
                //LocalDataBase.deleteAlarm("makingProduct")
                it.printStackTrace()
                this.onError(it.message ?: "")
            })
    }

    fun onTaking() {
        this.stopProgressTimer()
        var bundle = Bundle()
        bundle.putString("UI", "Finish")
        bundle.putLong("OrderId", this.orderId)
        LiveEventBus.get("SwitchUI").post(bundle)
    }

    fun onError(message: String) {
        this.stopProgressTimer()
        postToast(message, Toast.LENGTH_LONG)
        Thread.sleep(5 * 1000)
        var bundle = Bundle()
        bundle.putString("UI", "Menus")
        LiveEventBus.get("SwitchUI").post(bundle)
    }

    fun startProgressTimer() {
        this.mProgressTimer?.cancel()
        this.mProgressTimer = Timer()
        this.mProgressTimer?.schedule(1000, 1000) {
            var producingProgress = mDeviceService.producingProgress
            Log.d("process", "$producingProgress---" + (producingProgress * 7).toInt())
            var image = ""
            when ((producingProgress * 7).toInt()) {
                0 -> image = "res://${mApp.packageName}/${R.mipmap.process0}"
                1 -> image = "res://${mApp.packageName}/${R.mipmap.process1}"
                2 -> image = "res://${mApp.packageName}/${R.mipmap.process2}"
                3 -> image = "res://${mApp.packageName}/${R.mipmap.process3}"
                4 -> image = "res://${mApp.packageName}/${R.mipmap.process4}"
                5 -> image = "res://${mApp.packageName}/${R.mipmap.process5}"
                6 -> image = "res://${mApp.packageName}/${R.mipmap.process6}"
                7 -> image = "res://${mApp.packageName}/${R.mipmap.process7}"
                8 -> stopProgressTimer()
            }
            if (image != process.value) process.postValue(image)

            var status = mDeviceService.producingStatus
            if (status != EnumProducingStatus.PRODUCING) {
                //mDataService.insertLog("wvm->DeviceService.Finish")
                onTaking()
            }else if(status == EnumProducingStatus.TAKE_AWAY){

            }
        }
    }

    fun stopProgressTimer() {
        this.mProgressTimer?.cancel()
        this.mProgressTimer = null
    }
}